package com.zjx.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {Controller.class, RestController.class})
@ResponseBody
@Slf4j
public class ClobalExceptionHandler {

    @ExceptionHandler(value = {SQLIntegrityConstraintViolationException.class})
    public R exceptionHandler(SQLIntegrityConstraintViolationException e){
        log.info(e.getMessage());

        if(e.getMessage().contains("Duplicate entry")){
            String split[] = e.getMessage().split(" ");
            String msg = split[2]+"已存在！";
            return R.error(msg);
        }
        return R.error("未知失败！");
    }


    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> customExceptionHandler(Exception e){
        return R.error(e.getMessage());
    }
}
